const database = require("../../database/index");
const jwt = require("jsonwebtoken");
const config = require("../config");
const dayjs = require("dayjs");
// 用户登录
exports.login = (req, res) => {
    const userinfo = req.body;
    console.log(userinfo);
    if (!userinfo.username) {
        return res.response("用户名不能为空");
    };
    if (!userinfo.password) {
        return res.response("密码不能为空");
    };
    const sql = `select * from user where username=?`;
    database.query(sql, userinfo.username, function (err, results) {
        if (err) return res.response(err);
        if (results.length !== 1) return res.response("用户不存在");
        const compareResult = userinfo.password === results[0].password;
        if (!compareResult) {
            return res.response("密码错误");
        };
        const { id, username } = results[0];
        let user = {
            id,
            username,
        };
        const token = jwt.sign(user, config.jwtSecretKey, {
            expiresIn: config.expiresIn,
        });
        setTimeout(() => {
            res.send({
                code: 0,
                message: "登录成功！",
                result: {
                    token: "Bearer " + token,
                    userInfo: results[0],
                },
            });
        }, 800);
    });
};
// 用户注册
exports.register = (req, res) => {
    const sql = 'select * from user where username=?';
    const sql1 = "insert into user set ?";
    const randomNum = Math.floor(Math.random() * 90000) + 10000;;
    const nickname = '失物帮' + randomNum + '号';
    const index = Math.floor(Math.random() * 4) + 1;
    const picture = '/public/avatar/' + index + '.png'
    const created = dayjs().format("YYYY-MM-DD HH:mm:ss");
    database.query(sql, [req.body.username], function (err, results) {
        if (err) {
            return res.response(err);
        };
        if (results.length > 0) {
            return res.response("用户已存在");
        };
        database.query(
            sql1,
            {
                ...req.body,
                nickname,
                picture,
                created,
            },
            function (err) {
                if (err) return res.response(err);
                res.response("注册成功", 0);
            }
        );
    });

};

// 删除用户
exports.delete = (req, res) => {
    const { id } = req.body;
    const sql = "delete from user where id=?";
    database.query(sql, id, (err) => {
        if (err) return res.response(err);
        res.response("删除成功", 0);
    });
};

// 修改用户
exports.edit = (req, res) => {
    const { id } = req.body;
    let sql = "update user set ? where id=?";
    const updated = dayjs().format("YYYY-MM-DD HH:mm:ss");
    database.query(sql, [{ ...req.body, updated }, id], (err) => {
        if (err) return res.response(err);
        res.response("修改成功", 0);
    });
};

// 查询用户
exports.list = (req, res) => {
    const { content, page, pageSize, id } = req.body;
    let sql = "select * from user";
    let countSql = "select count(*) as total from user";
    let params = [];
    if (id) {
        sql += " where id=?";
        countSql += " where id=?";
        params.push(id)
    }
    if (content) {
        sql += sql.includes("where") ? " and (username like ? or nickname like ?)" : " where (username like ? or nickname like ?)";
        countSql += countSql.includes("where") ? " and (username like ? or nickname like ?)" : " where (username like ? or nickname like ?)";
        params.push(`%${content}%`, `%${content}%`)
    };
    database.query(countSql, params, function (countErr, countResult) {
        if (countErr) return res.response(countErr);
        const total = countResult[0] ? countResult[0].total : 0;
        if (page && pageSize) {
            const offset = (page - 1) * pageSize;
            sql += " LIMIT ? OFFSET ?";
            params.push(Number(pageSize), offset);
        }
        database.query(sql, params, function (err, result) {
            if (err) return res.response(err);
            return res.send({
                code: 0,
                message: "查询成功",
                total,
                result,
            });
        });
    });
};
// 查询不含这些id的用户
exports.list1 = (req, res) => {
    const { userIds } = req.body;
    if (!Array.isArray(userIds)) {
        return res.response("userIds 必须是数组");
    };
    let placeholders = userIds.map(() => '?').join(', ');
    let sql = `SELECT * FROM user WHERE id NOT IN (${placeholders})`;
    let params = userIds;
    database.query(sql, params, function (err, result) {
        if (err) return res.response(err);
        return res.send({
            code: 0,
            message: "查询成功",
            result,
        });
    });
};



